using System;
using System.Collections.Generic;
using PowerSearch.Core;
using System.Xml.Linq;
using System.Linq;

namespace PowerSearch.AppServices.Parser.Provider
{
	public class ESPNParser : BaseFeedParser
	{
		private const string FeedUrl = "http://sports.espn.go.com/espn/rss/news";

		public override string BaseUrl
		{
			get
			{

				return FeedUrl;
			}
		}

		#region Overridden methods

		protected internal override IList<Feed> ParseFeed(string data)
		{
			var feedList = new List<Feed>();
			var xmlDoc = XDocument.Parse(data);
			if (xmlDoc.Root != null)
			{
				var xmlns = xmlDoc.Root.GetDefaultNamespace();
				xmlDoc.Root.Descendants(xmlns + "item").ToList().ForEach(element => feedList.Add(CreateFeedItem(element, xmlns)));
			}
			return feedList;
		}

		#endregion

		#region Private methods
		private Feed CreateFeedItem(XElement xElement, XNamespace xmlns)
		{
			var title = xElement.Element(xmlns + "title") != null ? xElement.Element(xmlns + "title").Value : string.Empty;
			var clickUrl = xElement.Element(xmlns + "link") != null ? xElement.Element(xmlns + "link").Value : string.Empty;
			var description = xElement.Element(xmlns + "description") != null ? xElement.Element(xmlns + "description").Value : string.Empty;

			var feed = new Feed
			{
				Title = title,
				Description = StripOutDescription(description),
				ClickUrl = clickUrl,
			};
			return feed;
		}

		private string StripOutDescription(string description)
		{
			const string endTag = "</a>";
			if (description == null)
				return "";

			var index = description.LastIndexOf(endTag);
			if (index > -1)
				return description.Substring(index + endTag.Length, description.Length - (index + endTag.Length));

			return description;

		}
		#endregion
	}
}

